//
//  OEShopDetailViewController.m
//  OneEightyNine
//
//  Created by Mac on 2019/3/7.
//  Copyright © 2019 stoneobs. All rights reserved.
//

#import "OEShopDetailViewController.h"
#import "LGCultureButtonControl.h"
#import "OEGoodModel.h"
#import "OEShopGoodTableViewCell.h"
#import "OEShopCarViewController.h"
#import "OECommitViewController.h"
@interface OEShopDetailViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) NSMutableArray                     *cateArray;/**<  */
@property(nonatomic, strong) UITextField                     *searchTextFied;/**< 搜索 */
@property(nonatomic, strong) NSMutableArray <LGCultureButtonControl*>                    *controlArray;
@property(nonatomic, strong) NSString                     *cat_id;/**<  */
@property(nonatomic, strong) NSString                     *cat_name;/**<  */
@property(nonatomic, strong) STButton                     *titleButton;/**<  */

@property(nonatomic, strong) STLabel                     *moneyLable;/**<  */
@property(nonatomic, strong) STButton                     *shopCarButton;/**<  */
@property(nonatomic, strong) NSMutableArray<OEGoodModel*>                     *dataSouce;/**< 数据源 */
@property(nonatomic, strong) NSArray<OEGoodModel*>                     *shopCarSouce;/**< 数据源 */
@end
#define HEADER_HEIGHT 180
@implementation OEShopDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configSubView];
    [self configBootomView];
    [self updateShopCart];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self updateShopCart];
}

- (void)setCat_name:(NSString *)cat_name{
    _cat_name = cat_name;
    [self.titleButton setTitle:cat_name forState:UIControlStateNormal];
}
- (void)setShopCarSouce:(NSMutableArray<OEGoodModel *> *)shopCarSouce{
    _shopCarSouce = shopCarSouce;
    
}
- (void)updateShopCart{
    
    [OEHomeDataController sendFetchShopCarListRequestWithSupplier_id:self.model.supplier_id handle:^(NSString * _Nonnull cart_number, NSString * _Nonnull goods_price, NSArray * _Nonnull goods) {
        
        self.shopCarSouce = goods;
        [self.shopCarButton setBadgeValue:cart_number];
        self.moneyLable.text = [NSString stringWithFormat:@"%@",goods_price];
    }];
}
#pragma mark --subView
- (void)configBootomView{
    UIView * bootomView = [[UIImageView alloc] initWithFrame:CGRectMake(0, TMUtils.tabBarTop, UIScreenWidth, 49)];
    [self.view addSubview:bootomView];
    [self.view bringSubviewToFront:bootomView];
    bootomView.userInteractionEnabled = YES;
     UIView * grawView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth * 0.6, 49)];
    grawView.backgroundColor = [UIColor colorWithRed:59/255.0 green:61/255.0  blue:56/255.0  alpha:1];
    [bootomView addSubview:grawView];
    __weak typeof(self) weakSelf =  self;
    STButton * downbutton = [[STButton alloc] initWithFrame:CGRectMake(grawView.right, 0, 0.4 *UIScreenWidth, 49)
                                                  title:@"GO Down"
                                             titleColor:UIColor.whiteColor
                                              titleFont:18
                                           cornerRadius:0
                                        backgroundColor:OE_LIMITE_COLOR
                                        backgroundImage:nil
                                                  image:nil];
    downbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [bootomView addSubview:downbutton];
    [downbutton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedConfimButton];
    }];
    
    self.shopCarButton = [[STButton alloc] initWithFrame:CGRectMake(20, 0, 50, 50)
                                                  title:nil
                                             titleColor:nil
                                              titleFont:0
                                           cornerRadius:0
                                        backgroundColor:nil
                                        backgroundImage:nil
                                                  image:[UIImage imageNamed:@"100×100购物车"]];
    self.shopCarButton.centerY = bootomView.top + 10;
    [self.view addSubview:self.shopCarButton];
    [self.shopCarButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedShopCarButton];
    }];
    self.shopCarButton.clipsToBounds = NO;
    
    self.moneyLable = [[STLabel alloc] initWithFrame:CGRectMake(80, 0, 200, 49)
                                                    text:@"￥0.0"
                                               textColor:UIColor.whiteColor
                                                    font:15
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentLeft];
    self.moneyLable.userInteractionEnabled = NO;
    [bootomView addSubview:self.moneyLable];
    
}
- (void)configSubView{
    __weak typeof(self) weakSelf =  self;
    [self vhl_setNavBarBackgroundAlpha:0];
    
    self.searchTextFied = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth * 0.6, 34)];
    self.searchTextFied.placeholder = @"Search for goods";
    self.searchTextFied.returnKeyType = UIReturnKeySearch;
    self.searchTextFied.backgroundColor = UIColor.whiteColor;
    self.searchTextFied.layer.cornerRadius = self.searchTextFied.height / 2;
    self.searchTextFied.leftViewMode = UITextFieldViewModeAlways;
    STButton * searchButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 34, 34)
                                                        title:@""
                                                   titleColor:SecendTextColor
                                                    titleFont:0
                                                 cornerRadius:0
                                              backgroundColor:nil
                                              backgroundImage:nil
                                                        image:[UIImage imageNamed:@"24×26搜索"]];
    
    self.searchTextFied.leftView = searchButton;
    self.searchTextFied.delegate = self;
    searchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    self.navigationItem.titleView = self.searchTextFied;
    
    //头部
    ({
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, HEADER_HEIGHT)];
        [imageView sd_setImageWithURL:[NSURL URLWithString:self.model.supplier_logo]];
        [self.view addSubview:imageView];
        imageView.userInteractionEnabled = YES;
        
        UIVisualEffectView * visouView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
        visouView.frame = imageView.bounds;
        [imageView addSubview:visouView];
        
        UIImageView * subimageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 0, 50, 50)];
        [subimageView sd_setImageWithURL:[NSURL URLWithString:self.model.supplier_logo]];
        subimageView.bottom = imageView.height - 20;
        [imageView addSubview:subimageView];

        
        STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake( subimageView.right + 10,subimageView.top ,UIScreenWidth - 70, 30)
                                                         text:self.model.supplier_name
                                                    textColor:UIColor.whiteColor
                                                         font:16
                                                  isSizetoFit:NO
                                                textAlignment:NSTextAlignmentLeft];
        [imageView addSubview:titleLable];
        
        STLabel * stitleLable = [[STLabel alloc] initWithFrame:CGRectMake( subimageView.right + 10,subimageView.top ,UIScreenWidth - 70, 20)
                                                         text:[NSString stringWithFormat:@"%@ collection",self.model.fans_count]
                                                    textColor:UIColor.whiteColor
                                                         font:16
                                                  isSizetoFit:NO
                                                textAlignment:NSTextAlignmentLeft];
        [imageView addSubview:stitleLable];
        stitleLable.bottom = subimageView.bottom;
        
        STButton * colleButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)
                                                         title:nil
                                                    titleColor:nil
                                                     titleFont:0
                                                  cornerRadius:0
                                               backgroundColor:nil
                                               backgroundImage:nil
                                                         image:[UIImage imageNamed:@"46×46收藏"]];
        colleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        colleButton.right = UIScreenWidth - 15;
        [colleButton setClicAction:^(UIButton *sender) {
            [OEHomeDataController sendCollectShopWithSupplier_idRequest:weakSelf.model.supplier_id is_collect:@"0" handle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
                if (success) {
                    sender.hidden = YES;
                }
            }];
        }];
        colleButton.centerY = subimageView.centerY;
        colleButton.hidden = self.model.is_collect.boolValue;
        [imageView addSubview:colleButton];
    });
    ({
        //左侧
        [OEHomeDataController sendCateListRequestHandle:^(bool success, NSArray * _Nonnull array) {
            self.cateArray = array.mutableCopy;
            [self configMenuView];
        }];

        
    });
    
    ({
       //
        self.titleButton = [[STButton alloc] initWithFrame:CGRectMake(100, HEADER_HEIGHT, UIScreenWidth - 100, 44)
                                                         title:@""
                                                    titleColor:FirstTextColor
                                                     titleFont:15
                                                  cornerRadius:0
                                               backgroundColor:nil
                                               backgroundImage:nil
                                                         image:[UIImage imageNamed:@"6×24分类标题"]];
        [self.view addSubview:self.titleButton];
        self.titleButton.titleEdgeInsets = UIEdgeInsetsMake(0, 3, 0, 0);
        
        self.tableView.contentInset = UIEdgeInsetsZero;
        self.tableView.frame = CGRectMake(self.titleButton.left, self.titleButton.bottom, self.titleButton.width, TMUtils.tabBarTop - 30 - self.titleButton.bottom);
        __weak typeof(self) weakSelf =  self;
        STNoresultView * noresultView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 100, self.titleButton.width, 400) title:@"No More Data" buttonTitle:@"" buttonHandle:^(NSString *titleString) {

        }];
//        noresultView.left = -30;
        self.tableView.clipsToBounds = YES;
        noresultView.transform = CGAffineTransformMakeScale(0.8, 0.8);
        self.tableView.st_noreslutView = noresultView;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf sendListRequest];
        }];

    });
}
- (void)configMenuView{
    CGFloat buttonWith = 95;
    UIScrollView * scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, HEADER_HEIGHT, buttonWith, [TMUtils tabBarTop] -HEADER_HEIGHT  - 30 )];
    scrollView.backgroundColor = UIColorFromRGBA(0xF1F1F1);
    [self.view addSubview:scrollView];
    NSMutableArray * titlesArray = NSMutableArray.new;
    for (NSDictionary * dic in self.cateArray) {
        NSString * title = [dic[@"cat_name"] description];
        [titlesArray addObject:title];
    }
    NSArray * array = titlesArray;
    self.controlArray = [NSMutableArray new];
    __weak typeof(self) weakSelf =  self;
    for (NSInteger i = 0; i < array.count; i ++) {
        NSString * title = array[i];
        LGCultureButtonControl * control = [[LGCultureButtonControl alloc] initWithFrame:CGRectMake(0, 0, buttonWith, 52) title:title];
        [scrollView addSubview:control];
        [control setOnSelectedControl:^(LGCultureButtonControl *sender) {
            for (LGCultureButtonControl * existControl in self.controlArray) {
                existControl.selected = NO;
                sender.selected = YES;
                
            }
            NSDictionary * dic = weakSelf.cateArray[i];
            weakSelf.cat_id = [dic[@"cat_id"] description];
            weakSelf.cat_name = title;
            [weakSelf.tableView.mj_header beginRefreshing];

        }];
        control.top = i * 52;
        [self.controlArray addObject:control];
        if (i == 0) {
            control.selected = YES;
            NSDictionary * dic = weakSelf.cateArray[i];
            weakSelf.cat_id = [dic[@"cat_id"] description];
            weakSelf.cat_name = title;
            [weakSelf.tableView.mj_header beginRefreshing];
        }
        scrollView.contentSize = CGSizeMake(0, control.bottom);
    }
    scrollView.backgroundColor = UIColorFromRGBA(0xF1F1F1);
    [scrollView st_showRightLine:scrollView.height];
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return OEShopGoodTableViewCell.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    OEShopGoodTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[OEShopGoodTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    OEGoodModel * model = self.dataSouce[indexPath.row];
    cell.reduceButton.hidden = YES;
    cell.numLable.hidden = YES;
    cell.model = model;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    __weak typeof(self) weakSelf =  self;
    [cell.addButton setClicAction:^(UIButton *sender) {
        [OEHomeDataController addGoodToCar:model.goods_id handle:^(BOOL success, NSString *errorString, NSDictionary *resp) {
            if (success) {
                [SVProgressHUD showSuccessWithStatus:@"Add Shop Car Success"];
                [weakSelf updateShopCart];
            }
        }];
    }];
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OEGoodModel * model = self.dataSouce[indexPath.row];
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self.tableView.mj_header beginRefreshing];
        
    }
    return YES;
}
#pragma mark --Action Method
- (void)onSelctedConfimButton{
    if (!self.shopCarSouce.count) {
        [self st_showAlertTitle:@"The shopping cart was empty" message:@"" andWithBlock:^(NSString *name) {
            
        }];
        return;
    }
    
    OECommitViewController * vc = OECommitViewController.new;
    vc.dataSouce = self.shopCarSouce;
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)onSelctedShopCarButton{
    OEShopCarViewController * vc = OEShopCarViewController.new;
    vc.supplier_id = self.model.supplier_id;
    vc.model = self.model;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --NetWork Method
- (void)sendListRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * token = STUserManger.defult.loginedUser.token;
    if (token.length) {
        [paramDic setObject:token forKey:@"user_token"];
    }
    if (self.cat_id.length) {
        [paramDic setObject:self.cat_id forKey:@"cat_id"];
    }
    if (self.model.supplier_id.length) {
        [paramDic setObject:self.model.supplier_id forKey:@"supplier_id"];
    }
    if (self.searchTextFied.text.length) {
        [paramDic setObject:self.searchTextFied.text forKey:@"keyword"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"index.php?m=Front&c=Index&a=supplierGoodsList"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypeGet
                                          parameters:paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 //                                                 [STNetWrokManger shownNormalRespMsgWithResponse:responseObject];
                                                 NSArray * array = [responseObject valueForKey:@"content"][@"list"];
                                                 self.dataSouce = [OEGoodModel mj_objectArrayWithKeyValuesArray:array];
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self.tableView reloadData];
                                                 // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
                                                 //                                                 [self.tableView.mj_header endRefreshing];
                                                 DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error,NSError *originError) {
                                                 [SVProgressHUD dismiss];
                                                 self.dataSouce = [OEGoodModel mj_objectArrayWithKeyValuesArray:@[]];
                                                 [self.tableView.mj_header endRefreshing];
                                                 [self.tableView reloadData];
                                                 DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                                                            url,paramDic,error.desc,error.code);
                                             }];
}
@end
